package com.h4313.ghome.io;

import java.io.IOException;
import java.lang.ref.WeakReference;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

import com.h4313.ghome.model.TemperatureAllDay;

public class TemperaturesTask extends AsyncTask<String, Void, TemperatureAllDay>{
	
	public interface TemperaturesCallback {
		public void onTemperaturesFound(TemperatureAllDay temperatures);
	}

	WeakReference<TemperaturesCallback> tCallback;

	public TemperaturesTask(TemperaturesCallback callback) {
		tCallback = new WeakReference<TemperaturesCallback>(callback);
	}

	@Override
	protected TemperatureAllDay doInBackground(String... urls) {
		TemperatureAllDay tempObj = new TemperatureAllDay();
		try {

			String contentAsString = NetworkHelper.downloadUrl(urls[0], 20000,
					20000);
			JSONObject root;
			root = new JSONObject(contentAsString);
			JSONArray data = root.getJSONArray("data");
			for(int i = 0; i<data.length();i++){
				JSONObject oneHour = data.getJSONObject(i);
				Double temp = oneHour.getDouble("value");
				tempObj.addTemperature(temp);
			}
//			Integer id = root.getInt("id_sensor");
//			String date = root.getString("date");

//			SimpleDateFormat format = new SimpleDateFormat(
//					"yyyy-MM-dd HH:mm:ss", Locale.FRANCE);
//			Date dateobj = format.parse(date);

//			tempObj.setIdCapteur(id);
//			tempObj.setDate(dateobj);
			Log.d("Margot", "okok");
			return tempObj;

		} catch (IOException e) {
			System.out
					.print("Unable to retrieve web page. URL may be invalid.");
			e.printStackTrace();
			return null;
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@Override
	protected void onPostExecute(TemperatureAllDay result) {

		if (tCallback.get() != null) {

			tCallback.get().onTemperaturesFound(result);
		}
	}

}
